'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 修复退款/取消订单的返利状态
 * 
 * 功能：
 * 1. 查找所有状态为 'refunded' 或 'cancelled'，但 commission_status 不是 'cancelled' 的订单
 * 2. 根据订单的 commission_status 核减用户的实际返利金额
 * 3. 更新订单的 commission_status 为 'cancelled'
 * 
 * 核减逻辑：
 * - 如果 commission_status 为 'pending'：核减 commission_pending（待激活佣金）
 * - 如果 commission_status 为 'activated'：核减 commission_available 和 commission_total（可提现佣金）
 * - 如果 commission_status 为 null 或其他值：只更新状态，不核减金额（因为可能从未发放）
 */
exports.main = async (event, context) => {
  console.log('========================================');
  console.log('开始修复退款/取消订单的返利状态...');
  console.log('========================================');
  
  try {
    // 查找所有状态为 'refunded' 或 'cancelled'，但 commission_status 不是 'cancelled' 的订单
    const ordersToFix = await db.collection('orders').where({
      status: dbCmd.in(['refunded', 'cancelled']),
      commission_status: dbCmd.neq('cancelled'),
      commission_amount: dbCmd.gt(0)
    }).get();
    
    if (ordersToFix.data.length === 0) {
      console.log('✅ 没有需要修复的订单');
      return { 
        success: true,
        fixedCount: 0, 
        message: '没有需要修复的订单' 
      };
    }
    
    console.log(`📋 发现 ${ordersToFix.data.length} 条需要修复的订单`);
    console.log('');
    
    let fixedCount = 0;
    let errorCount = 0;
    const fixDetails = [];
    
    for (const order of ordersToFix.data) {
      const orderId = order._id;
      const promoterId = order.promoter_id;
      const commissionAmount = order.commission_amount;
      const commissionStatus = order.commission_status;
      const orderStatus = order.status;
      
      console.log(`\n--- 处理订单 ${orderId} ---`);
      console.log(`订单状态: ${orderStatus}`);
      console.log(`返利金额: ${commissionAmount} 分`);
      console.log(`当前返利状态: ${commissionStatus || 'null'}`);
      console.log(`推荐人ID: ${promoterId || '无'}`);
      
      try {
        // 如果没有推荐人，只更新订单状态
        if (!promoterId) {
          await db.collection('orders').doc(orderId).update({
            commission_status: 'cancelled'
          });
          console.log(`✅ 订单 ${orderId} 无推荐人，已更新返利状态为 'cancelled'`);
          fixedCount++;
          fixDetails.push({
            orderId,
            action: '更新状态',
            reason: '无推荐人'
          });
          continue;
        }
        
        // 根据当前的 commission_status 决定如何核减佣金
        if (commissionStatus === 'pending') {
          // 待激活佣金：核减 commission_pending
          await db.collection('users').doc(promoterId).update({
            commission_pending: dbCmd.inc(-commissionAmount)
          });
          console.log(`✅ 已核减推荐人 ${promoterId} 的待激活佣金 ${commissionAmount} 分`);
          
          fixDetails.push({
            orderId,
            promoterId,
            action: '核减待激活佣金',
            amount: commissionAmount
          });
        } else if (commissionStatus === 'activated') {
          // 已激活佣金：核减 commission_available 和 commission_total
          await db.collection('users').doc(promoterId).update({
            commission_available: dbCmd.inc(-commissionAmount),
            commission_total: dbCmd.inc(-commissionAmount)
          });
          console.log(`✅ 已核减推荐人 ${promoterId} 的可提现佣金 ${commissionAmount} 分`);
          
          fixDetails.push({
            orderId,
            promoterId,
            action: '核减可提现佣金',
            amount: commissionAmount
          });
        } else {
          // commission_status 为 null 或其他值：可能从未发放佣金，只更新状态
          console.log(`⚠️ 订单 ${orderId} 的返利状态为 ${commissionStatus || 'null'}，可能从未发放佣金，只更新状态`);
          
          fixDetails.push({
            orderId,
            promoterId,
            action: '仅更新状态',
            reason: `原状态为 ${commissionStatus || 'null'}，可能未发放`
          });
        }
        
        // 更新订单的返利状态为 'cancelled'
        await db.collection('orders').doc(orderId).update({
          commission_status: 'cancelled'
        });
        console.log(`✅ 订单 ${orderId} 的返利状态已更新为 'cancelled'`);
        
        fixedCount++;
      } catch (err) {
        errorCount++;
        console.error(`❌ 修复订单 ${orderId} 失败:`, err.message);
        fixDetails.push({
          orderId,
          action: '失败',
          error: err.message
        });
      }
    }
    
    console.log('');
    console.log('========================================');
    console.log('修复完成！');
    console.log(`✅ 成功修复: ${fixedCount} 条`);
    console.log(`❌ 失败: ${errorCount} 条`);
    console.log('========================================');
    
    return { 
      success: true,
      fixedCount, 
      errorCount,
      totalCount: ordersToFix.data.length,
      details: fixDetails,
      message: `成功修复 ${fixedCount} 条订单的返利状态${errorCount > 0 ? `，失败 ${errorCount} 条` : ''}`
    };
  } catch (err) {
    console.error('❌ 修复过程发生错误:', err);
    return {
      success: false,
      error: err.message,
      message: '修复过程发生错误'
    };
  }
};

